package com.crocodileQ.util;


/***
 * @Author 鳄鱼杆
 * @Date 2025/4/10 21:07
 */

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

import java.text.Normalizer;

public class PinyinConverter {

    public static String slugify(String input) {
        if (input == null || input.isEmpty()) return "";

        // Step 1: 中文转拼音
        String normalized = convertToPinyin(input);

        // Step 2: 转ASCII并过滤特殊字符
        normalized = Normalizer.normalize(normalized, Normalizer.Form.NFD)
                .replaceAll("[^\\p{ASCII}]", "") // 去除非ASCII字符
                .replaceAll("[^a-z0-9\\-\\s]", "") // 过滤非法字符
                .trim();

        // Step 3: 空格转连字符并合并
        return normalized.replaceAll("\\s+", "-")  // 空格转连字符
                .replaceAll("-+", "-");           // 合并连续连字符
    }

    // 汉字转拼音（复用之前的代码）
    private static String convertToPinyin(String input) {
        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
        format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);

        StringBuilder result = new StringBuilder();
        for (char c : input.toCharArray()) {
            if (isChinese(c)) {
                try {
                    String[] pinyin = PinyinHelper.toHanyuPinyinStringArray(c, format);
                    if (pinyin != null) result.append(pinyin[0]);
                } catch (BadHanyuPinyinOutputFormatCombination e) {
                    result.append(c);
                }
            } else {
                result.append(Character.toLowerCase(c));
            }
        }
        return result.toString();
    }

    private static boolean isChinese(char c) {
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
        return ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS;
    }


}